Products = new Meteor.Collection("product");
Tracks = new Meteor.Collection("tracks");

//All keys in the products table
var keys = new Object();//Its a map
var values = new Object();
var categories = new Object();

if (Meteor.isClient) {


function getAllKeys(prods){
var tempKeys = new Object();
prods.forEach(function(doc){
for(var key in doc)
      {
        if(doc.hasOwnProperty(key) && key != "_id" && key != "category"){
            //alert(key);
            tempKeys[key] = 'placeholder';
           }
      }

});
keys = tempKeys;
}


function getAllValues(prods, key)
{
var tempValues = new Object();
prods.forEach(function(doc){
var value = doc[key];
tempValues[value] = 'placeholder';
}
);
values = tempValues;
}


/*get all categories available*/
function getAllCategories(prods)
{

prods.forEach(function(doc){
var category = doc.category;
categories[category] = 'placeholder';

});
}

function buildAndSetQuery(key,value){

if(null != key && null != value)
{
var query = Session.get("current_query") && key != "category" ? Session.get("current_query") : {};
query[key]=value.toString();
Session.set("current_query",query);
if(key=='category')
  {
   
   Session.set("current_track",null);
  }
}
return "";
}


function buildQueryForNotSelected(val){
  var nqObj = {};
  var nqValues = new Array();
  var query = Session.get("current_query");
  var proj = Session.get("projection");
  val = val.toString();
  if(null != query && null != proj && null != val)
  {
    //Get the filter key
    var key = Object.keys(proj)[0];
    nqObj = query[key];
    if(null != nqObj)
     {
       nqValues = nqObj["$nin"];
       nqValues[nqValues.length] = val;
     }
     else
     {
       nqObj = {};
       nqValues = new Array();
       nqValues[0] = val;
       
     }
     nqObj["$nin"] = nqValues;
     query[key] = nqObj;
     Session.set("current_query",query);
     
     var notSelecteds = new Array();
     var temp = new Object();
     temp[key] = nqObj;
     temp['time'] = new Date();
     
     var track = Session.get("current_track");
     if(null == track)
       {
         track = new Object();
        }
     notSelecteds = track["unselected"];
     if(null == notSelecteds)
       {
         notSelecteds = new Array();
        }
     notSelecteds[notSelecteds.length] = temp;

     track["current_query"] = query;
     track["unselected"] = notSelecteds;
     Session.set("current_track",track);

  }
}

function buildAndSetProjection(key){
 if(null != key){
   var proj = {};
   key = key.toString();
   proj[key] = '1';
   Session.set("projection",proj);
   }
}

Template.buycontent.available_products = function(){

  var qJson = Session.get("current_query");
if(null != qJson)
{
  var products = Products.find(qJson);

  return products;
}
};


Template.buycontent.available_filters = function(){
  var qJson = Session.get("current_query");
  if(null != qJson)
  {
  var products = Products.find(qJson);
  getAllKeys(products);
  return Object.keys(keys);
  }
};

Template.buycontent.available_values = function(){
 var qJson = Session.get("current_query");
 var proj = Session.get("projection");
 if(null != qJson && null != proj)
 {
   var prods = Products.find(qJson,proj);
   var projKey = Object.keys(proj);
   getAllValues(prods,projKey[0]);
   return Object.keys(values);  
 }
};

Template.buycontent.query_json = function(){

var qJson = Session.get("current_query");

return JSON.stringify(qJson);

};


Template.buycontent.products = function(){
   var prods = Products.find();
   getAllKeys(prods);
   
   var allKeys = Object.keys(keys);

   return allKeys;
};


Template.buycontent.categories = function(){
   var prods = Products.find();
   getAllCategories(prods);

   
   var allKeys = Object.keys(categories);

   return allKeys;
};


Template.buycontent.tracks = function(){

  var track = Session.get("current_track");
  if(null != track)
 {
  var proj = Session.get("projection");
  var key = Object.keys(proj)[0];
  var unselecteds = track["unselected"];
  var tracks = new Array();
  for(var i=0 ;i < unselecteds.length ; i++)
  {
    var unSelected = unselecteds[i];
    if(unSelected[key] != null)
      {
        var track = new Object();
        track["nin"] = unSelected[key];
        track["time"] = unSelected["time"];
        
        tracks[tracks.length] = JSON.stringify(track);
      }
   }
  return tracks;
 }
};

Template.buycontent.deselected_values = function(){

var track = Session.get("current_track");
  if(null != track)
 {
  var proj = Session.get("projection");
  var key = Object.keys(proj)[0];
  var unselecteds = track["unselected"];
  var deSelectedValues = new Object();
  for(var i=0 ;i < unselecteds.length ; i++)
  {
    var unSelected = unselecteds[i];
    if(unSelected[key] != null)
      {
        var nin = new Object();
        nin = unSelected[key];
        var values = nin["$nin"];
        for(var i = 0 ;i<values.length;i++)
           {
             deSelectedValues[values[i]] = 'placeholder';
            }
      }
   }
   return Object.keys(deSelectedValues);
 }

};



  Template.buycontent.events({
    'click .category': function () {
    buildAndSetQuery("category",this);
    },
    'click .filter': function () {
    buildAndSetProjection(this);
    },
    'click .selected': function () {
    buildQueryForNotSelected(this);
    }
    });


}

if (Meteor.isServer) {

  var prods = [
{"category" : "mobile", "make" : "samsung", "model" : "Galaxy S4", "ram" : "4GB", "internal_storage" : "8GB", "expandable_storage" : "32GB", "processor" : "4core", "processor_model" : "snapdragon s5", "os" : "android4.2.0", "type" : "candybar", "product_details" : [  "http://visitbooks.com" ], "video_reviews" : [  "http://youtube.com" ], "text_reviews" : [  "http://google.com" ] },
{"category" : "mobile", "make" : "apple", "model" : "iphone 3gs", "ram" : "4GB", "internal_storage" : "8GB", "expandable_storage" : "32GB", "processor" : "2core", "processor_model" : "apple a5 chipset", "os" : "ios", "type" : "candybar", "product_details" : [  "http://visitbooks.com" ], "video_reviews" : [  "http://youtube.com" ], "text_reviews" : [  "http://google.com" ] },
{"category" : "mobile", "make" : "lg", "model" : "optimus", "ram" : "2GB", "internal_storage" : "4GB", "expandable_storage" : "16GB", "processor" : "1 core", "processor_model" : "lg chipset", "os" : "android", "type" : "flip phone", "product_details" : [  "http://visitbooks.com" ], "video_reviews" : [  "http://youtube.com" ], "text_reviews" : [  "http://google.com" ] },
{"category" : "mobile", "make" : "apple", "model" : "iphone 4g", "ram" : "2GB", "internal_storage" : "16GB", "expandable_storage" : "64GB", "processor" : "8core", "processor_model" : "mediatek a3850", "os" : "ios", "type" : "candybar", "product_details" : [  "http://visitbooks.com" ], "video_reviews" : [  "http://youtube.com" ], "text_reviews" : [  "http://google.com" ] },
{"category" : "footwear", "make" : "lakhani", "model" : "hawai", "type" : "unknown", "material" : "rubber", "product_details" : [  "http://visitbooks.com" ], "video_reviews" : [  "http://youtube.com" ], "text_reviews" : [  "http://google.com" ] },
{"category" : "Television", "make" : "LG", "model" : "series 6", "type" : "flat screen", "screen_size" : "32", "warrenty" : "2 years", "discounts" : [  "flat 50%",  "EMI Offer" ], "product_details" : [  "http://visitbooks.com" ], "video_reviews" : [  "http://youtube.com" ], "text_reviews" : [  "http://google.com" ] }
    ];

  Meteor.startup(function () {
    // code to run on server at startup

if (Products.find().count() === 0) {
  for(var i =0 ; i < prods.length ; i++)
  {
    Products.insert(prods[i]);
   }
}


  });
}




